<template>
  <el-form-item class="rrs-main" prop="rrsMain" label="解析记录">
    <form-table rule-prop="rrs" :rule="rrsRule" :data="state.rrs">
      <template #default="{ row, $index }">
        <form-table-column prop="name" label="主机记录" width="136">
          <el-input
            v-model="row.name"
            :class="getErrorClass($index, 'name') || `no-need-error`"
            placeholder="请输入主机记录"
          />
        </form-table-column>
        <form-table-column prop="type" label="记录类型" width="256">
          <el-select
            v-model="row.type"
            class="w-full no-need-error"
            placeholder="请选择记录类型"
          >
            <el-option
              v-for="item in logOpts"
              :key="item.label"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </form-table-column>
        <form-table-column prop="value" label="记录值" width="256">
          <el-input
            v-model="row.value"
            :disabled="isDisabledValue"
            :class="getErrorClass($index, 'value')"
            :placeholder="getValuePlaceHolder(row.type)"
          />
        </form-table-column>
        <form-table-column prop="TTL" label="TTL" width="136">
          <el-select v-model="row.ttl" class="w-full no-need-error">
            <el-option
              v-for="item in ttlOpts"
              :key="item.label"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </form-table-column>
        <form-table-column prop="action">
          <el-button
            v-if="!(!$index && state.rrs.length <= 1)"
            :icon="Delete"
            link
            type="danger"
            @click="state.rrs.splice($index, 1)"
          />
        </form-table-column>
      </template>
    </form-table>
    <div class="add-btn" @click="state.rrs.push(initMoreItem())">
      <el-icon size="9">
        <plus />
      </el-icon>
      <div class="text-sm ml-2">添加一行</div>
    </div>
  </el-form-item>
</template>

<script setup lang="ts">
import { Delete, Plus } from '@element-plus/icons-vue'
import type { FormInstance, FormItemRule } from 'element-plus'
import type { Ref } from 'vue'

import { getValuePlaceHolder, logOpts, ttlOpts } from '@/config/enums/record'

import type { RrsItem } from '../type'

interface IProps {
  label: string
  isDisabledValue?: boolean
  formState: {
    domains?: string
    rrs: RrsItem[]
  }
}

const props = defineProps<IProps>()
const state = computed(() => props.formState)

const formRef = inject('formRef', ref()) as Ref<FormInstance>

type ChildError = {
  index: number
  key: string
}

const childError = inject('childError', ref([])) as Ref<ChildError[]>

const addChildError = (index: number, key: string) => {
  if (childError.value.some(v => v.index === index && v.key === key)) return
  childError.value.push({ index, key })
}

const delChildError = (index: number, key: string) => {
  const delIdx = childError.value.findIndex(
    v => v.index === index && v.key === key
  )
  delIdx > -1 && childError.value.splice(delIdx, 1)
}

const getErrorClass = (index: number, key: string) => {
  return childError.value.some(v => v.index === index && v.key === key)
    ? 'is-child-error'
    : ''
}

const validatorFn = (validator, value) => validator(null, value)
const rrsRule: FormItemRule = {
  trigger: 'blur',
  // 服务器IP、CDN域名、邮件服务域名
  validator: (rule, value: RrsItem) => {
    formRef.value?.clearValidate('rrsMain')
    const index = +rule.field!.split('.')[1]
    let flag: boolean | Error = true

    // 主机记录
    if (value.name) {
      flag = validatorFn(
        hostValidate(() => state.value?.domains ?? ''),
        value.name!
      )
      if (flag !== true) {
        delChildError(index, 'value')
        addChildError(index, 'name')
        return flag
      }
    }

    if (!props.isDisabledValue) {
      // 记录值
      if (!!value.name && !value.value) {
        delChildError(index, 'name')
        addChildError(index, 'value')
        return new Error('请输入记录值')
      }

      if (value.value) {
        flag = validatorFn(
          logValueValidate(() => value.type!),
          value.value!
        )

        if (flag !== true) {
          delChildError(index, 'name')
          addChildError(index, 'value')
          return flag
        }
      }
    }

    delChildError(index, 'name')
    delChildError(index, 'value')
    return flag
  }
}

const initMoreItem = (): RrsItem => ({
  name: '',
  value: '',
  type: 'A',
  ttl: 600
})

// 保证至少有一行
watchEffect(() => {
  if (!state.value.rrs.length) {
    state.value.rrs.push(initMoreItem())
  }
})
</script>

<style lang="scss" scoped>
.add-btn {
  cursor: pointer;
  display: flex;
  user-select: none;
  justify-content: center;
  align-items: center;
  border: 1px dotted rgba(219, 221, 226, 1);
  border-radius: 4px;
  height: 32px;
  width: 768px;
  margin-top: 8px;
  &:hover {
    color: rgba(#595e70, 0.9);
  }
  .el-icon {
    color: #595e70;
  }
}
</style>
<style lang="scss">
.rrs-main {
  --custom-error-color: var(--el-color-danger);
  &.is-error {
    .form-table__tr.is-error {
      .form-table__td {
        --el-color-danger: var(--custom-error-color);
      }
    }
    .no-need-error {
      --el-color-danger: var(--el-border-color);
    }
  }
  .form-table__tr.is-error {
    .form-table__td {
      --el-color-danger: var(--el-border-color);
    }
    .is-child-error {
      --el-color-danger: var(--custom-error-color);
    }
  }
  .el-button--danger {
    --el-color-danger: var(--custom-error-color);
  }
}
</style>
